package com.wzy.oa_sys.service.impl.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.oa_sys.mapper.task.TaskMapper;
import com.wzy.oa_sys.mapper.user.DeptMapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.task.OaTask;
import com.wzy.oa_sys.model.pojo.user.OaUser;
import com.wzy.oa_sys.model.request.notice.NoticeReq;
import com.wzy.oa_sys.model.request.task.TaskReq;
import com.wzy.oa_sys.model.response.task.TaskResp;
import com.wzy.oa_sys.service.notice.NoticeService;
import com.wzy.oa_sys.service.task.TaskService;
import com.wzy.oa_sys.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, OaTask> implements TaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private NoticeService noticeService;
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public List<TaskResp> getTaskList() {
        List<TaskResp> taskList = new ArrayList<>();
        List<OaTask> oaTaskList = taskMapper.selectList(null);
        oaTaskList.forEach(oaTask -> {
            TaskResp build = TaskResp.builder()
                    .id(oaTask.getNTaskId())
                    .type(oaTask.getCType())
                    .title(oaTask.getCTitle())
                    .desc(oaTask.getCDesc())
                    .starttime(oaTask.getDtStartTime())
                    .deadline(oaTask.getDtDeadline())
                    .promoter(userMapper.selectUserById(oaTask.getNUserId()).getCRealName())
                    .promoterid(oaTask.getNUserId())
                    .deptid(oaTask.getNDeptId())
                    .evaluate(oaTask.getCEvaluate())
                    .exreason(oaTask.getCExReason())
                    .priority(oaTask.getNPriority())
                    .reviewerId(oaTask.getCReviewerId())
                    .build();
            if(oaTask.getNDeptId()!= 0){
                build.setDeptname(deptMapper.selectDeptById(oaTask.getNDeptId()).getCDeptName());
            }else{
                build.setDeptname("全部门");
            }
            if(oaTask.getCReviewerId()!= 0){
                build.setReviewer(userMapper.selectUserById(oaTask.getCReviewerId()).getCRealName());
            }
            if(oaTask.getCState().equals("1")){
                build.setState("待办");
            }else if(oaTask.getCState().equals("2")){
                build.setState("进行中");
            }else if(oaTask.getCState().equals("3")){
                build.setState("已完成");
            }
            if(oaTask.getNChargeId()!= 0){
                build.setCharge(userMapper.selectUserById(oaTask.getNChargeId()).getCRealName());
            }
            String s = oaTask.getCRecipient();
            if (!s.equals("[]")) {
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                StringBuilder sb = new StringBuilder();
                for (int receiver : result) {
                    sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                }
                build.setRecipient(sb.toString().substring(0, sb.length() - 1));
            }else{
                build.setRecipient("所有人");
            }
            taskList.add(build);
        });
        // 按优先级排序
        Collections.sort(taskList, Comparator.comparingInt(TaskResp::getPriority));
        return taskList;
    }

    @Override
    public void addTask(TaskReq taskReq, long l) {
        OaTask oaTask = new OaTask();
        oaTask.setCType(taskReq.getType());
        oaTask.setCTitle(taskReq.getTitle());
        oaTask.setCDesc(taskReq.getDesc());
        LocalDateTime starttime = taskReq.getStarttime();
        oaTask.setDtStartTime(starttime.plusHours(8));
        LocalDateTime deadline = taskReq.getDeadline();
        oaTask.setDtDeadline(deadline.plusHours(8));
        oaTask.setNUserId(l);
        oaTask.setNDeptId(taskReq.getDeptname());
        oaTask.setCState(taskReq.getState());
        oaTask.setCRecipient(taskReq.getReceiverList().toString());
        oaTask.setNPriority(taskReq.getPriority());
        oaTask.setNChargeId(taskReq.getCharge());
        oaTask.setCReviewerId(taskReq.getReviewer());
        oaTask.setCExReason(taskReq.getExreason());
        taskMapper.insert(oaTask);
    }

    @Override
    public int deleteTaskById(Integer id) {
        return taskMapper.deleteTaskById(id);
    }

    @Override
    public TaskResp getTaskDetailById(Integer id) {
        QueryWrapper<OaTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_task_id", id);
        OaTask oaTask = taskMapper.selectOne(queryWrapper);
        if (oaTask != null) {
            TaskResp taskResp = TaskResp.builder()
                    .id(id)
                    .deptid(oaTask.getNDeptId())
                    .promoterid(oaTask.getNUserId())
                    .chargeid(oaTask.getNChargeId())
                    .reviewerId(oaTask.getCReviewerId())
                    .type(oaTask.getCType())
                    .title(oaTask.getCTitle())
                    .desc(oaTask.getCDesc())
                    .starttime(oaTask.getDtStartTime())
                    .deadline(oaTask.getDtDeadline())
                    .state(oaTask.getCState())
                    .priority(oaTask.getNPriority())
                    .evaluate(oaTask.getCEvaluate())
                    .exreason(oaTask.getCExReason())
                    .build();
            if(userMapper.selectUserById(oaTask.getNUserId())!= null){
                taskResp.setPromoter(userMapper.selectUserById(oaTask.getNUserId()).getCRealName());
            }
            if(userMapper.selectUserById(oaTask.getNChargeId())!= null){
                taskResp.setCharge(userMapper.selectUserById(oaTask.getNChargeId()).getCRealName());
            }
            if(deptMapper.selectDeptById(oaTask.getNDeptId())!= null){
                taskResp.setDeptname(deptMapper.selectDeptById(oaTask.getNDeptId()).getCDeptName());
            }else{
                taskResp.setDeptname("全部门");
            }
            if(oaTask.getCReviewerId()!= 0){
                if(userMapper.selectUserById(oaTask.getCReviewerId())!= null){
                    taskResp.setReviewer(userMapper.selectUserById(oaTask.getCReviewerId()).getCRealName());
                }
            }
            if(oaTask.getCState().equals("1")){
                taskResp.setState("待办");
            }else if(oaTask.getCState().equals("2")){
                taskResp.setState("进行中");
            }else if(oaTask.getCState().equals("3")){
                taskResp.setState("已完成");
            }
            String s = oaTask.getCRecipient();
            if (!s.equals("[]")) {
                String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
                int[] result = Arrays.stream(numbers)
                        .mapToInt(Integer::parseInt)
                        .toArray();
                StringBuilder sb = new StringBuilder();
                for (int receiver : result) {
                    sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
                }
                taskResp.setRecipient(sb.toString().substring(0, sb.length() - 1));
            }else{
                taskResp.setRecipient("所有人");
            }
            return taskResp;
        }

        return null;
    }

    @Override
    public List<TaskResp> getMyTaskList(long l) {
        // 获取所有任务
        List<OaTask> oaTasks = taskMapper.selectList(null);

        // 过滤符合条件的任务
        List<OaTask> filteredTasks = oaTasks.stream()
                .filter(task -> task.getNChargeId() == l ||task.getNUserId() == l ||
                        (!task.getCRecipient().equals("[]")  &&
                                Arrays.stream(task.getCRecipient().replace("[", "").replace("]", "").split(","))
                                        .map(String::trim)
                                        .map(Long::parseLong)
                                        .collect(Collectors.toList())
                                        .contains(l)))
                .collect(Collectors.toList());
        List<TaskResp> collect = filteredTasks.stream()
                .map(this::convertToTaskResp)
                .collect(Collectors.toList());
        // 将过滤后的 OaTask 对象转换为 TaskResp 对象
        Collections.sort(collect, Comparator.comparingInt(TaskResp::getPriority));
        return collect;
    }

    @Override
    public List<TaskResp> getICanApprovedTask(long l) {
        QueryWrapper<OaUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_user_id", l);
        OaUser oaUser = userMapper.selectOne(queryWrapper);
        List<TaskResp> taskRespList = getTaskList();

        // 判断角色并进行相应的过滤
        if (oaUser.getNRole() == 1) {
            return taskRespList.stream().filter(task -> task.getState().equals("待审批"))
                    .collect(Collectors.toList()); // 角色为1，返回全部请假列表
        } else if (oaUser.getNRole() == 2) {
            // 角色为2，仅保留 reviewId 等于 userId 的数据
            return taskRespList.stream()
                    .filter(task -> task.getState().equals("待审批"))
                    .filter(task -> task.getReviewerId() == l) // 过滤为用户可审核的所有数据
                    .collect(Collectors.toList()); // 收集结果为列表
        }
        return taskRespList;
    }

    @Override
    public void updateTheTask(TaskReq taskReq) {
        QueryWrapper<OaTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_task_id", taskReq.getId());
        OaTask oaTask = taskMapper.selectOne(queryWrapper);
        if (oaTask != null) {
            oaTask.setCExReason(taskReq.getExreason());
            oaTask.setCState(taskReq.getState());
            if(taskReq.getState().equals("进行中")){
                oaTask.setCState("2");
            }else if(taskReq.getState().equals("已完成")){
                oaTask.setCState("3");
            }
            taskMapper.updateTaskById(oaTask);
        }else{
            System.out.println("更新失败");
        }
    }

    @Override
    public List<TaskResp> getSomeTasks(long l) {
        List<TaskResp> myTaskList = getMyTaskList(l);
        if(myTaskList.size() > 6){
            myTaskList = myTaskList.subList(0, 6);
        }
        return myTaskList;
    }

    @Override
    public void updateTask(TaskReq taskReq,HttpServletRequest request) {
        Long userId = jwtUtil.extractUserId(request);
        System.out.println(taskReq);
        QueryWrapper<OaTask> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_task_id", taskReq.getId());
        OaTask oaTask = taskMapper.selectOne(queryWrapper);
        //记录是否修改
        Boolean flag = false;
        if(oaTask != null){
            if(taskReq.getType()!= null&&!taskReq.getType().equals("")){
                oaTask.setCType(taskReq.getType());
                flag = true;
            }
            if(taskReq.getTitle()!= null&&!taskReq.getTitle().equals("")){
                oaTask.setCTitle(taskReq.getTitle());
                flag = true;
            }
            if(taskReq.getDesc()!= null&&!taskReq.getDesc().equals("")){
                oaTask.setCDesc(taskReq.getDesc());
                flag = true;
            }
            LocalDateTime starttime = taskReq.getStarttime();
            oaTask.setDtStartTime(starttime.plusHours(8));
            LocalDateTime deadline = taskReq.getDeadline();
            oaTask.setDtDeadline(deadline.plusHours(8));
            oaTask.setNDeptId(taskReq.getDeptname());
            if(taskReq.getState()!= null&&!taskReq.getState().equals("")){
                oaTask.setCState(taskReq.getState());
                flag = true;
            }
            if(taskReq.getReceiverList()!= null&&!taskReq.getReceiverList().equals("")){
                oaTask.setCRecipient(taskReq.getReceiverList().toString());
                flag = true;
            }
            if(taskReq.getPriority()!=0){
                oaTask.setNPriority(taskReq.getPriority());
                flag = true;
            }
            if(taskReq.getCharge()!=0){
                oaTask.setNChargeId(taskReq.getCharge());
                flag = true;
            }
            if(taskReq.getReviewer()!=0){
                oaTask.setCReviewerId(taskReq.getReviewer());
                flag = true;
            }
            if(taskReq.getExreason()!=null&&!taskReq.getExreason().equals("")){
                oaTask.setCExReason(taskReq.getExreason());
                flag = true;
            }
            if(flag==true){
                oaTask.setNUserId(userId);
                NoticeReq noticeReq = new NoticeReq();
                noticeReq.setType("更新");
                noticeReq.setState(2);
                noticeReq.setTitle("任务更新通知");
                noticeReq.setDesc("您有一条任务更新通知，请注意查看。可点击链接查看具体信息。");
                noticeReq.setReleasetime(LocalDateTime.now().minusHours(8));
                noticeReq.setDeptname(taskReq.getDeptname());
                String cRecipient = oaTask.getCRecipient();
                if(!cRecipient.equals("[]")){
                    String[] numbers = cRecipient.replaceAll("[\\[\\]\\s]", "").split(",");
                    int[] result = Arrays.stream(numbers)
                            .mapToInt(Integer::parseInt)
                            .toArray();
                    List<Long> receiverList = Arrays.stream(result)
                            .mapToObj(Long::valueOf)
                            .collect(Collectors.toList());
                    noticeReq.setReceiverList(receiverList);
                }else{
                    noticeReq.setReceiverList(new ArrayList<>());
                }
                noticeReq.setReviewer(userId);
                noticeReq.setExamine("1");
                noticeReq.setExReason("任务状态更新，不需审核");
                noticeReq.setLinkId(taskReq.getId());
                noticeReq.setLinkType("task");
                noticeService.addNotice(noticeReq,userId);

            }
            int update = taskMapper.update(oaTask, queryWrapper);
            System.out.println("更新任务情况"+update);

        }

    }

    private TaskResp convertToTaskResp(OaTask oaTask) {
        TaskResp resp = TaskResp.builder()
                .id(oaTask.getNTaskId())
                .type(oaTask.getCType())
                .title(oaTask.getCTitle())
                .desc(oaTask.getCDesc())
                .starttime(oaTask.getDtStartTime())
                .deadline(oaTask.getDtDeadline())
                .promoterid(oaTask.getNUserId())
                .deptid(oaTask.getNDeptId())
                .exreason(oaTask.getCExReason())
                .reviewerId(oaTask.getCReviewerId())
                .state(oaTask.getCState())
                .priority(oaTask.getNPriority())
                .promoter(userMapper.selectUserById(oaTask.getNUserId()).getCRealName())
                .evaluate(oaTask.getCEvaluate())
                .build();
        if(oaTask.getCReviewerId()!= 0){
            resp.setReviewer(userMapper.selectUserById(oaTask.getCReviewerId()).getCRealName());
        }
        if(oaTask.getCState().equals("1")){
            resp.setState("待办");
        }else if(oaTask.getCState().equals("2")){
            resp.setState("进行中");
        }else if(oaTask.getCState().equals("3")){
            resp.setState("已完成");
        }
        if(oaTask.getNDeptId()!= 0){
            resp.setDeptname(deptMapper.selectDeptById(oaTask.getNDeptId()).getCDeptName());
        }else{
            resp.setDeptname("全部门");
        }
        if(oaTask.getNChargeId()!= 0){
            resp.setCharge(userMapper.selectUserById(oaTask.getNChargeId()).getCRealName());
        }
        String s = oaTask.getCRecipient();
        if (!s.equals("[]")) {
            String[] numbers = s.replaceAll("[\\[\\]\\s]", "").split(",");
            int[] result = Arrays.stream(numbers)
                    .mapToInt(Integer::parseInt)
                    .toArray();
            StringBuilder sb = new StringBuilder();
            for (int receiver : result) {
                sb.append(userMapper.selectUserById(receiver).getCRealName()).append(",");
            }
            resp.setRecipient(sb.toString().substring(0, sb.length() - 1));
        }else{
            resp.setRecipient("所有人");
        }
        return resp;
    }
}
